package storage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import entity.User;

public class UserAccessManager 
{
	private static String filePath="data";
	private static String fileName="user.xml";
	
	public List<User> userList;
 
	public UserAccessManager()
	{
		if (!isUserFileExists()) initDatabaseFile();
		refreshList();
	}
	public boolean isPasswordMatching(String user, String password)
	{
		int index=isUserExists(user);
		if(index==-1)
			return false;
		User e=userList.get(index);
		String r=e.getPassword();
		if(password.equalsIgnoreCase(r))
			return true;
		return false;
	}
	public boolean isUserFileExists()
	{
		File file = new File(filePath+"/"+fileName);
		if (file.exists()) return true;
		else return false;
	}
	
	public int isUserExists(String Username)
	{
		for (int i=0;i<userList.size();i++) if (userList.get(i).getUsername().compareTo(Username)==0) return i;
		return -1;
	}
	
	public void initDatabaseFile()
	{
		 try 
		 {
			 new File(filePath).mkdirs();
			 
			 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			 Document doc = docBuilder.newDocument();
			 Element rootElement = doc.createElement("UserDatabase");
			 doc.appendChild(rootElement);
		 
			 TransformerFactory transformerFactory = TransformerFactory.newInstance();
			 Transformer transformer = transformerFactory.newTransformer();
			 DOMSource source = new DOMSource(doc);
			 StreamResult result = new StreamResult(new File(filePath+"/"+fileName));
		 
			 transformer.transform(source, result);
		 
		 } 
		 catch (ParserConfigurationException pce) 
		 {
			 pce.printStackTrace();
		 } 
		 catch (TransformerException tfe) 
		 {
			 tfe.printStackTrace();
		 }
	}
	
	public void refreshList()
	{
		userList = loadUsers();
	}
	
	public List<User> loadUsers()
	{
		List<User> list = new ArrayList<User>();
		try 
		{
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	        Document doc = docBuilder.parse (new File(filePath+"/"+fileName));
	        
	        NodeList userList = doc.getElementsByTagName("User");
	        for (int i=0;i<userList.getLength();i++)
	        {
	        	Node userNode = userList.item(i);
	        	User user = new User(userNode.getAttributes().getNamedItem("Username").getNodeValue(),
	        						userNode.getAttributes().getNamedItem("Password").getNodeValue());
	        	list.add(user);
	        }
	        
	        return list;
		}
		catch (SAXException SE)
		{
			return null;
		} 
		catch (ParserConfigurationException e) 
		{
			return null;
		} 
		catch (IOException e) 
		{
			return null;
		}
		
	}
	
	public void saveUsers()
	{
		saveUsers(userList);
	}
	
	public void saveUsers(List<User> list)
	{
		try 
		 {
			 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			 Document doc = docBuilder.newDocument();
			 Attr attribute;
			 Element rootElement = doc.createElement("UserDatabase");
			 doc.appendChild(rootElement);
			 
			 for (int i=0;i<list.size();i++)
			 {
				 User user = list.get(i);
				 Element databaseElement = doc.createElement("User");
				 
				 attribute = doc.createAttribute("Username");
				 attribute.setValue(user.getUsername());
				 databaseElement.setAttributeNode(attribute);
				 
				 attribute = doc.createAttribute("Password");
				 attribute.setValue(user.getPassword());
				 databaseElement.setAttributeNode(attribute);
				 
				 rootElement.appendChild(databaseElement);
			 }
		 
			 TransformerFactory transformerFactory = TransformerFactory.newInstance();
			 Transformer transformer = transformerFactory.newTransformer();
			 DOMSource source = new DOMSource(doc);
			 StreamResult result = new StreamResult(new File(filePath+"/"+fileName));
		 
			 transformer.transform(source, result);
		 
		 } 
		 catch (ParserConfigurationException pce) 
		 {
			 JOptionPane.showMessageDialog(null, pce.toString());
		 } 
		 catch (TransformerException tfe) 
		 {
			 JOptionPane.showMessageDialog(null, tfe.toString());
		 }
	}
	
	public boolean addUser(User newUser)
	{
		if (isUserExists(newUser.getUsername())!=-1) return false;
		userList.add(newUser);
		saveUsers(userList);
		return true;
	}
	
	public boolean updateUsername(String oldName,String newName)
	{
		int index = isUserExists(oldName);
		if (index==-1) return false;
		if (isUserExists(newName)!=-1) return false;
		userList.get(index).setUsername(newName);
		saveUsers(userList);
		return true;
	}
	
	public boolean deleteUserByName(String Username) 
	{
		int index = isUserExists(Username);
		if (index==-1) return false;
		userList.remove(index);
		saveUsers(userList);
		return true;
	}
	
	
}
